﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media.Animation;
using Clarity.Phone.Controls.Animations;
using Microsoft.Phone.Controls;
using TradeMeSDK;

namespace TradeMo
{
    public partial class MainView 
    {
        private SelectorHelper<SearchType> _selector;
        private GeneralSearchCriteriaView _generalSearchCriteriaView;
		private CriteriaBikesView _criteriaBikesView;
		private CriteriaUsedCarsView _criteriaUsedCarsView;
        private CriteriaBoatsView _criteriaBoatsView;
        private CriteriaJobsView _criteriaJobsView;
        private CriteriaPropertyForSaleView _criteriaPropertyForSaleView;
        private CriteriaPropertyRentalView _criteriaPropertyRentalView;
        private CriteriaPropertyForSaleView _criteriaPropertyOpenHomeView;
        private CriteriaPropertyFlatmateView _criteriaPropertyFlatmateView;
        private MainViewModel _viewModel;

        public MainView()
        {
            InitializeComponent();

            AnimationContext = LayoutRoot;

            _viewModel = App.Model;
            DataContext = _viewModel;

            //panorama.DefaultItem = myTradeMePanoramaItem;

            LayoutUpdated += OnLayoutUpdated;
        }

        private void OnLayoutUpdated(object s, EventArgs e)
        {
            LayoutUpdated -= OnLayoutUpdated;
            _viewModel.CheckTrademeCatalog(this);
        }

        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            if (!App.TradeMe.IsLoggedIn)
                NavigationService.Navigate(new Uri("/TradeMeLoginView.xaml", UriKind.Relative));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            _viewModel.UpdateViewModel();
            _selector = new SelectorHelper<SearchType> { Items = _viewModel.SearchTypes };

            if (App.TradeMe.IsLoggedIn)
                _viewModel.UpdateMyTradeMe();

            if (App.Model.Setup.HideBackground)
                AnimationGrid.Background.Opacity = 0.0;
            else
                AnimationGrid.Background.Opacity = 1.0;
        }

		private void HighlightElement(FrameworkElement element)
		{
			HighlightStoryboard.Stop();
			foreach (Timeline timeline in HighlightStoryboard.Children)
				Storyboard.SetTarget(timeline, element);
			HighlightStoryboard.Begin();
		}

        private void TextBox_KeyUp(object sender, KeyEventArgs e)
        {
            if ((e.Key != Key.Enter) &&
                (e.PlatformKeyCode != 10)) return;

            e.Handled = true;
            _viewModel.SearchText = SearchTextBox.Text;     // Doesn't bind until you loose focus
            _viewModel.DoSearch();

            panorama.Focus(); // Close keyboard
        }

        //private void DidYouMeanText_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        //{
        //    _viewModel.ChangeSearchTextToDidYouMean();
        //}


        private Popup _searchCriteriaPopup;
        private Popup SearchCriteriaPopup
        {
            get
            {
                if (_searchCriteriaPopup == null)
                {
                    _searchCriteriaPopup = new Popup();
                    LayoutRoot.Children.Add(_searchCriteriaPopup);
                }
                return _searchCriteriaPopup;
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (SearchCriteriaPopup.IsOpen)
            {
                IBackButtonController backButtonController = SearchCriteriaPopup.Child as IBackButtonController;
                if (backButtonController != null && !backButtonController.CanClose())
                {
                    //VisualStateManager.GoToState(this, "EnabledState", true);
                	e.Cancel = true;
                    return;
                }

                if (backButtonController != null)
                    backButtonController.Close(() =>
                            {
                                SearchCriteriaPopup.IsOpen = false;
                                VisualStateManager.GoToState(this, "EnabledState", true);
                            });
                else
                {
                    SearchCriteriaPopup.IsOpen = false;
                    VisualStateManager.GoToState(this, "EnabledState", true);
                }
                e.Cancel = true;
                return;
            }
            base.OnBackKeyPress(e);
        }

        private void GestureListener_Tap(object sender, GestureEventArgs e)
        {
            ShowSearchOptions();
        }

        private void ShowSearchOptions()
        {
            switch (_viewModel.SelectedSearchTypeSelector.Item)
            {
                case SearchType.General:
                    _generalSearchCriteriaView = new GeneralSearchCriteriaView(_viewModel.GeneralSearchCriteriaModel);
                    _generalSearchCriteriaView.RefreshAction = () =>
                                                                   {
                                                                       _generalSearchCriteriaView.Close(() =>
                                                                                                            {
                                                                                                                SearchCriteriaPopup.IsOpen = false;
                                                                                                                VisualStateManager.GoToState(this, "EnabledState", true);
                                                                                                            });
                                                                       _viewModel.DoSearch();
                                                                   };
                    SearchCriteriaPopup.Child = _generalSearchCriteriaView;
                    //SearchCriteriaPopup.HorizontalAlignment = HorizontalAlignment.Center;
                    SearchCriteriaPopup.IsOpen = true;
                    VisualStateManager.GoToState(this, "DisabledState", false);
                    break;

                case SearchType.Bikes:
                    _criteriaBikesView = new CriteriaBikesView(_viewModel.CriteriaBikesModel);
                    _criteriaBikesView.RefreshAction = () =>
                                                           {
                                                               _criteriaBikesView.Close(() =>
                                                                                            {
                                                                                                SearchCriteriaPopup.IsOpen = false;
                                                                                                VisualStateManager.GoToState(this, "EnabledState", true);
                                                                                            });
                                                               _viewModel.DoSearch();
                                                           };
                    SearchCriteriaPopup.Child = _criteriaBikesView;
                    SearchCriteriaPopup.IsOpen = true;
                    VisualStateManager.GoToState(this, "DisabledState", false);
                    break;

                case SearchType.UsedCars:
                    _criteriaUsedCarsView = new CriteriaUsedCarsView(_viewModel.CriteriaUsedCarsModel);
                    _criteriaUsedCarsView.RefreshAction = () =>
                                                              {
                                                                  _criteriaUsedCarsView.Close(() =>
                                                                                                  {
                                                                                                      SearchCriteriaPopup.IsOpen = false;
                                                                                                      VisualStateManager.GoToState(this, "EnabledState", true);
                                                                                                  });
                                                                  _viewModel.DoSearch();
                                                              };
                    SearchCriteriaPopup.Child = _criteriaUsedCarsView;
                    SearchCriteriaPopup.IsOpen = true;
                    VisualStateManager.GoToState(this, "DisabledState", false);
                    break;

                case SearchType.Boats:
                    _criteriaBoatsView = new CriteriaBoatsView(_viewModel.CriteriaBoatsModel);
                    _criteriaBoatsView.RefreshAction = () =>
                                                           {
                                                               _criteriaBoatsView.Close(() =>
                                                                                            {
                                                                                                SearchCriteriaPopup.IsOpen = false;
                                                                                                VisualStateManager.GoToState(this, "EnabledState",true);
                                                                                            });
                                                               _viewModel.DoSearch();
                                                           };
                    SearchCriteriaPopup.Child = _criteriaBoatsView;
                    SearchCriteriaPopup.IsOpen = true;
                    VisualStateManager.GoToState(this, "DisabledState", false);
                    break;

                case SearchType.Jobs:
                    _criteriaJobsView = new CriteriaJobsView(_viewModel.CriteriaJobsModel);
                    _criteriaJobsView.RefreshAction = () =>
                                                          {
                                                              _criteriaJobsView.Close(() =>
                                                                                          {
                                                                                              SearchCriteriaPopup.IsOpen = false;
                                                                                              VisualStateManager.GoToState(this, "EnabledState",true);
                                                                                          });
                                                              _viewModel.DoSearch();
                                                          };
                    SearchCriteriaPopup.Child = _criteriaJobsView;
                    SearchCriteriaPopup.IsOpen = true;
                    VisualStateManager.GoToState(this, "DisabledState", false);
                    break;

                case SearchType.Residential:
                    _criteriaPropertyForSaleView = new CriteriaPropertyForSaleView(_viewModel.CriteriaPropertyForSaleModel);
                    _criteriaPropertyForSaleView.RefreshAction = () =>
                                                                     {
                                                                         _criteriaPropertyForSaleView.Close(() =>
                                                                                                                {
                                                                                                                    SearchCriteriaPopup.IsOpen = false;
                                                                                                                    VisualStateManager.GoToState(this, "EnabledState",true);
                                                                                                                });
                                                                         _viewModel.DoSearch();
                                                                     };
                    SearchCriteriaPopup.Child = _criteriaPropertyForSaleView;
                    SearchCriteriaPopup.IsOpen = true;
                    VisualStateManager.GoToState(this, "DisabledState", false);
                    break;

                case SearchType.Rental:
                    _criteriaPropertyRentalView = new CriteriaPropertyRentalView(_viewModel.CriteriaPropertyRentalModel);
                    _criteriaPropertyRentalView.RefreshAction = () =>
                    {
                        _criteriaPropertyRentalView.Close(() =>
                        {
                            SearchCriteriaPopup.IsOpen = false;
                            VisualStateManager.GoToState(this, "EnabledState", true);
                        });
                        _viewModel.DoSearch();
                    };
                    SearchCriteriaPopup.Child = _criteriaPropertyRentalView;
                    SearchCriteriaPopup.IsOpen = true;
                    VisualStateManager.GoToState(this, "DisabledState", false);
                    break;

                case SearchType.OpenHomes:
                    _criteriaPropertyOpenHomeView = new CriteriaPropertyForSaleView(_viewModel.CriteriaPropertyOpenHomeModel);
                    _criteriaPropertyOpenHomeView.RefreshAction = () =>
                    {
                        _criteriaPropertyOpenHomeView.Close(() =>
                        {
                            SearchCriteriaPopup.IsOpen = false;
                            VisualStateManager.GoToState(this, "EnabledState", true);
                        });
                        _viewModel.DoSearch();
                    };
                    SearchCriteriaPopup.Child = _criteriaPropertyOpenHomeView;
                    SearchCriteriaPopup.IsOpen = true;
                    VisualStateManager.GoToState(this, "DisabledState", false);
                    break;

                case SearchType.Flatmates:
                    _criteriaPropertyFlatmateView = new CriteriaPropertyFlatmateView(_viewModel.CriteriaPropertyFlatmateModel);
                    _criteriaPropertyFlatmateView.RefreshAction = () =>
                    {
                        _criteriaPropertyFlatmateView.Close(() =>
                        {
                            SearchCriteriaPopup.IsOpen = false;
                            VisualStateManager.GoToState(this, "EnabledState", true);
                        });
                        _viewModel.DoSearch();
                    };
                    SearchCriteriaPopup.Child = _criteriaPropertyFlatmateView;
                    SearchCriteriaPopup.IsOpen = true;
                    VisualStateManager.GoToState(this, "DisabledState", false);
                    break;


                default:
                    MessageBox.Show("No additional options for " + _viewModel.SelectedSearchTypeSelector.Title + " search");
                    break;
            }
        }

        private void GestureListener_Hold(object sender, GestureEventArgs e)
        {
            SelectSearchType();
        }

        private void SelectSearchType()
        {
            VisualStateManager.GoToState(this, "DisabledState", false);
            _selector.OpenPopup(LayoutRoot, () =>
                                                {
                                                    _viewModel.SelectedSearchTypeSelector = _selector.Selected;
                                                    VisualStateManager.GoToState(this, "EnabledState", true);
                                                });
        }

        private void OpenListing(int listingId)
        {
            NavigationService.Navigate(new Uri("/ListingView.xaml?ListingId=" + listingId, UriKind.Relative));
        }

        //private void ResultsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    var selectedItem = ResultsListBox.SelectedItem as SearchResultItem;
        //    _viewModel.SelectedResult = selectedItem;
        //    //ResultsListBox.SelectedItem = null;

        //    if (selectedItem == null) return;

        //    OpenListing(selectedItem.Listing.ListingId);
        //}


        //private void LoadMoreText_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        //{
        //    _viewModel.DoSearchMore();
        //}

        private void RecentlyViewListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (RecentlyViewListBox.SelectedItem == null) return;

            var selectedItem = RecentlyViewListBox.SelectedItem as SearchResultItem;
            RecentlyViewListBox.SelectedItem = null;
            if (selectedItem == null) return;

            OpenListing(selectedItem.Listing.ListingId);
        }

        private void RecentSearchesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (RecentSearchesListBox.SelectedItem == null) return;

            var selected = RecentSearchesListBox.SelectedItem as SearchCriteria;
            RecentSearchesListBox.SelectedItem = null;
            if (selected == null) return;

            _viewModel.DoShowRecentSearch(selected);
            SearchTextBox.Text = selected.SearchString;
        }

        private void ClearRecentButton_Click(object sender, RoutedEventArgs e)
        {
            _viewModel.Recent.Clear();
        }

        private void CategoryListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (CategoryListBox.SelectedItem == null) return;
            var selected = CategoryListBox.SelectedItem as Category;
            CategoryListBox.SelectedItem = null;
            if (selected == null) return;

            _viewModel.SelectedCategory = selected;

			HighlightElement(BrowseToButton);

            // If there are no children, then begin the browse
            if ((selected.Subcategories == null) ||
                (selected.Subcategories.Count == 0))
            {
                BrowseToButton_Click(null, null);
            }
        }

        private void Breadcrumbs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Breadcrumbs.SelectedItem == null) return;
            var breadcrumb = Breadcrumbs.SelectedItem as Category;
            Breadcrumbs.SelectedItem = null;
            if (breadcrumb == null) return;

            _viewModel.SelectedCategory = breadcrumb;

			HighlightElement(BrowseToButton);
        }

        private void HomeButton_Click(object sender, RoutedEventArgs e)
        {
            _viewModel.SelectedCategory = null;
        }

        private void BrowseToButton_Click(object sender, RoutedEventArgs e)
        {
            if (_viewModel.SelectedCategory == null) return;

            var criteria = App.Model.GeneralSearchCriteriaModel.Criteria.Clone();
            criteria.SearchString = null;
            criteria.Category = _viewModel.SelectedCategory.Number;

            string hash = criteria.GetHashCode().ToString();
            new IsolatedStorageRepository<SearchGeneralCriteria>(hash + ".criteria").Write(criteria);

            NavigationService.Navigate(new Uri("/SearchResultsView.xaml?type=category&criteria=" + hash,
                                               UriKind.Relative));
        }

        private void RefreshSummaryButton_Click(object sender, RoutedEventArgs e)
        {
        	_viewModel.GetMyTradeMe();
        }

        private void BuyingButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/BuyingView.xaml", UriKind.Relative));
        }

        private void SellingButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/SellingView.xaml", UriKind.Relative));
        }

        private void AboutButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/About.xaml", UriKind.Relative));
        }

        private void searchTypeButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	SelectSearchType();
        }

        private void searchOptionsButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	ShowSearchOptions();
        }

        private void SearchTextBox_GotFocus(object sender, System.Windows.RoutedEventArgs e)
        {
        	HighlightElement(searchOptionsButton);
        }

    }
}